<?php

namespace common\models\c2\entity;

use common\components\AttachmentBehavior;
use common\helpers\Tool;
use cza\base\models\statics\ImageSize;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * This is the model class for table "{{%device}}".
 *
 * @property integer $id
 * @property integer $id2
 * @property integer $community_id
 * @property integer $building_number_id
 * @property integer $unit_id
 * @property string $name
 * @property integer $type
 * @property integer $status
 * @property string $password
 * @property string $remarks
 */
class Device extends \cza\base\models\ActiveRecord
{

    use \common\traits\AttachmentTrait;

    // public function fields()
    // {
    //     return [
    //         'id',
    //         'id2',
    //         'community_id',
    //         'building_number_id',
    //         'unit_id',
    //         'type',
    //         'status',
    //         'cover' => function ($model) {
    //             return $model->getInitialPreviewUrls('cover', ImageSize::ORGINAL);
    //         },
    //     ];
    // }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%device}}';
    }

    public function behaviors()
    {
        return [
            'attachmentsBehavior' => [
                'class' => AttachmentBehavior::className(),
                'attributesDefinition' => [
                    'cover' => [
                        'class' => \common\models\c2\entity\EntityAttachmentImage::className(),
                        'validator' => 'image',
                        'rules' => [
                            'maxFiles' => 1,
                            'uploadRequired' => Yii::t('app.c2', 'Photo must upload.'),
                            // 'skipOnEmpty' => false,
                            // 'skipOnError' => false,
                            'extensions' => Yii::$app->params['config']['upload']['imageWhiteExts'],
                            // 'extensions' => ['jpg'],
                            'maxSize' => Yii::$app->params['config']['upload']['maxFileSize'],
                            // 'maxSize' => '2048',
                        ]
                    ]
                ]
            ],

        ]; // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['community_id', 'building_number_id', 'unit_id', 'type', 'status', 'id2'], 'integer'],
            [['name', 'password'], 'required'],
            [['name', 'password', 'remarks'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'community_id' => Yii::t('app.c2', 'Community ID'),
            'building_number_id' => Yii::t('app.c2', 'Building Number ID'),
            'unit_id' => Yii::t('app.c2', 'Unit ID'),
            'name' => Yii::t('app.c2', 'Name'),
            'type' => Yii::t('app.c2', 'Type'),
            'status' => Yii::t('app.c2', 'Status'),
            'password' => Yii::t('app.c2', 'Password'),
            'remarks' => Yii::t('app.c2', 'Remarks'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\DeviceQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\DeviceQuery(get_called_class());
    }
    
    /**
    * setup default values
    **/
    public function loadDefaultValues($skipIfSet = true) {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getCommunity()
    {
        return $this->hasOne(Community::className(), ['id2' => 'community_id']);
    }

    public function getBuildingNumber()
    {
        return $this->hasOne(BuildingNumber::className(), ['id2' => 'building_number_id']);
    }

    public function getUnit()
    {
        return $this->hasOne(Unit::className(), ['id2' => 'unit_id']);
    }

    public function beforeSave($insert)
    {

        $data = [
            // 'id' => $this->id2,
            'community_id' => $this->community_id,
            'building_number_id' => $this->building_number_id,
            'unit_id' => $this->unit_id,
            'name' => $this->name,
            'type' => $this->type,
            'password' => $this->password,
            'status' => $this->status,
            'remarks' => $this->remarks,
        ];

        if ($this->isNewRecord) {
            $url = \Yii::$app->params['api_url'] . '/api/Building/SetAddDevice?supplier_id=' . Yii::$app->params['supplier_id'];
        } else {
            $data['id'] = $this->id2;
            $url = \Yii::$app->params['api_url'] . '/api/Building/SetUpdateDevice?supplier_id=' . Yii::$app->params['supplier_id'];
        }

        // 同步到第三方平台
        $data = Json::encode($data);
        $result = Tool::curlPost($url, $data);
        Yii::info($result);

        $result = json_decode($result, true);
        if ($result['Status'] && $result['Status'] == 1) {
            if ($this->isNewRecord) {
                $this->id2 = $result['Ext'];
            }
            return parent::beforeSave($insert); // TODO: Change the autogenerated stub
        }

        Yii::$app->session->setFlash($this->getMessageName(), $result['Msg']);
        return false;
    }

}
